/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.agent;



import of.hotswapinject.core.common.Const;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

public class JarFileHelper {
    public static String getLocalJarPath() {
        return getLocalJarPath(AgentAttach.class);
    }

    public static String getLocalJarPath(Class baseClass) {
        ProtectionDomain domain = baseClass.getProtectionDomain();
        CodeSource codeSource = domain.getCodeSource();
        URL localUrl = codeSource.getLocation();
        String path = null;
        try {
            path = URLDecoder.decode(
                    localUrl.getFile().replace("+", "%2B"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static String getLocalJarParentPath() {
        String jarPath = getLocalJarPath();
        return jarPath.substring(0, jarPath.lastIndexOf("/"));
    }


    public static String getContent(JarFile jarFile, String resourcePath) throws IOException {
        ZipEntry entry = jarFile.getEntry(resourcePath);
        InputStream stream = jarFile.getInputStream(entry);
        InputStreamReader isr = new InputStreamReader(stream, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String lineSeparator = Const.NEWLINE;
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append(lineSeparator);
        }
        String content = sb.toString();
        return content;
    }
}